package com.mc.fastkit.dialog.animator

import android.animation.ArgbEvaluator
import android.animation.ValueAnimator
import android.graphics.Color
import androidx.core.animation.doOnEnd
import androidx.interpolator.view.animation.FastOutSlowInInterpolator
import com.mc.fastkit.dialog.XDialog
import com.mc.fastkit.ext.cast

/**
 * 背景动画工具，执行[startColor]到[bgColor]的渐变动画
 * @author: MasterChan
 * @date: 2023-12-29 10:27
 */
open class BgAnimator : AbsDialogAnimator() {

    protected open val evaluator = ArgbEvaluator()
    protected open var startColor = Color.TRANSPARENT
    protected open var endColor = Color.TRANSPARENT
    open var bgColor = Color.TRANSPARENT
        set(value) {
            field = value
            this.endColor = value
        }

    override fun init() {
        target!!.setBackgroundColor(startColor)
    }

    /**
     * 显示
     * @param onEnd 自定义时此方法必须回调，否则会影响后续的事件
     * [XDialog.onStart]->[XDialog.onShowAnimator]
     */
    override fun show(onEnd: (() -> Unit)?) {
        val animator = ValueAnimator.ofObject(evaluator, startColor, endColor)
        animator.addUpdateListener { target!!.setBackgroundColor(it.animatedValue as Int) }
        animator.interpolator = FastOutSlowInInterpolator()
        onEnd?.let { callback -> animator.doOnEnd { callback.invoke() } }
        animator.setDuration(duration).start()
    }

    override fun dismiss(onEnd: (() -> Unit)?) {
        val animator = ValueAnimator.ofObject(evaluator, endColor, startColor)
        animator.addUpdateListener { target!!.setBackgroundColor(it.animatedValue as Int) }
        animator.interpolator = FastOutSlowInInterpolator()
        onEnd?.let { callback -> animator.doOnEnd { callback.invoke() } }
        animator.setDuration(duration).start()
    }

    open fun evaluateBgColor(fraction: Float) {
        endColor = evaluator.evaluate(fraction, startColor, bgColor).cast()
        target?.setBackgroundColor(endColor)
    }
}